/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAAbstractFeaturePageViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 30/10/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAAbstractFeaturePageViewController.h"



@interface BAAbstractFeaturePageViewController () {
    NSInteger currentPageIndex;
    NSInteger prefferedNextPageIndex;
}

@property (strong, nonatomic) UIScrollView* scrollView;


@property (nonatomic, strong) UIButton* forwardButton;
@property (nonatomic, strong) UIButton* backwardButton;

@end

@implementation BAAbstractFeaturePageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    currentPageIndex = 0;
    prefferedNextPageIndex = 0;
    _scrollView = [UIScrollView new];
    [self.view addSubview:self.scrollView];
    [BAUtils setViewToFillParent:self.scrollView];
    [self.scrollView setDelegate:self];
    self.scrollView.scrollsToTop = NO;
    
    [self.view setBackgroundColor:[UIColor clearColor]];
    [self.scrollView setBackgroundColor:[UIColor clearColor]];
    [self.scrollView setDelaysContentTouches:YES];
    [self.scrollView setPagingEnabled:YES];
    [self.scrollView setShowsHorizontalScrollIndicator:NO];
    
    //    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    //    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics: 0 views:@{@"scrollView": self.scrollView}]];
    //    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics: 0 views:@{@"scrollView": self.scrollView}]];
    
    _forwardButton = [UIButton new];
    _backwardButton = [UIButton new];
    
    [self.forwardButton addTarget:self action:@selector(forwardButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.backwardButton addTarget:self action:@selector(backwardButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.forwardButton setImage:[UIImage imageNamed:@"forwardbutton-shadow-white"] forState:UIControlStateNormal];
    [self.backwardButton setImage:[UIImage imageNamed:@"backbutton-shadow-white"] forState:UIControlStateNormal];
    
    [self.view addSubview:self.forwardButton];
    [self.view addSubview:self.backwardButton];
    
    [self.backwardButton setAlpha:0];
    
    self.forwardButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.backwardButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[forwardButton(40)]|" options:0 metrics: 0 views:@{@"forwardButton": self.forwardButton}]];
    [self.view addConstraint:[NSLayoutConstraint
                              constraintWithItem:self.forwardButton
                              attribute:NSLayoutAttributeCenterY
                              relatedBy:NSLayoutRelationEqual
                              toItem:self.view
                              attribute:NSLayoutAttributeCenterY
                              multiplier:1.0f
                              constant:0.0f]];
    [self.forwardButton addConstraint:[NSLayoutConstraint constraintWithItem:self.forwardButton
                                                                   attribute:NSLayoutAttributeHeight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                  multiplier:1.0f
                                                                    constant:40]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backwardButton(40)]" options:0 metrics: 0 views:@{@"backwardButton": self.backwardButton}]];
    [self.view addConstraint:[NSLayoutConstraint
                              constraintWithItem:self.backwardButton
                              attribute:NSLayoutAttributeCenterY
                              relatedBy:NSLayoutRelationEqual
                              toItem:self.view
                              attribute:NSLayoutAttributeCenterY
                              multiplier:1.0f
                              constant:0.0f]];
    [self.backwardButton addConstraint:[NSLayoutConstraint constraintWithItem:self.backwardButton
                                                                    attribute:NSLayoutAttributeHeight
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:nil
                                                                    attribute:NSLayoutAttributeNotAnAttribute
                                                                   multiplier:1.0f
                                                                     constant:40]];
    [self finishSetupView];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.scrollView.frame = self.view.bounds;
    
    CGFloat xOffset = 0;
    for (BAAbstractFeatureViewButton* button in self.featureButtons) {
        //[button setFrame:CGRectMake(xOffset, 0, self.scrollView.frame.size.width, 180)];
        [button setFrame:CGRectMake(xOffset, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
        xOffset += self.scrollView.frame.size.width;
    }
    [self.scrollView setContentSize:CGSizeMake(xOffset, self.scrollView.frame.size.height)];
    [self updateButtonsAlpha];
    [self.view layoutIfNeeded];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)removeFeatureButtons
{
    if (self.isViewLoaded) {
        for (UIView* view in self.featureButtons) {
            [view removeFromSuperview];
        }
        [self.scrollView setContentOffset:CGPointZero];
    }
    _featureButtons = nil;
}

-(void)setFeatureButtons:(NSArray *)featureButtons
{
    [self removeFeatureButtons];
    _featureButtons = featureButtons;
    BAAbstractFeatureViewButton* previousButton = nil;
    
    for (BAAbstractFeatureViewButton* currentButton in featureButtons) {
        
        [currentButton addTarget:self action:@selector(featureButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:currentButton];
        currentButton.translatesAutoresizingMaskIntoConstraints = NO;
        
        if (previousButton == nil) {
            [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[currentButton(==scrollView)]" options:0 metrics: 0 views:@{@"currentButton":currentButton, @"scrollView": self.scrollView}]];
        } else{
            [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[previousButton][currentButton(==scrollView)]" options:0 metrics: 0 views:@{@"currentButton":currentButton,@"previousButton":previousButton, @"scrollView": self.scrollView}]];
        }
        [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[currentButton(==scrollView)]|" options:0 metrics: 0 views:@{@"currentButton":currentButton, @"scrollView": self.scrollView}]];
        
        previousButton = currentButton;
    }
    if (previousButton != nil) {
        [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[previousButton]|" options:0 metrics: 0 views:@{@"previousButton":previousButton}]];
    }
    
}

-(void)finishSetupView
{
    [self.scrollView setContentOffset:CGPointZero animated:NO];
    if (self.isViewLoaded) {
        if (self.featureButtons.count <=1) {
            [self.forwardButton setHidden:YES];
            [self.backwardButton setHidden:YES];
        } else {
            [self.forwardButton setHidden:NO];
            [self.backwardButton setHidden:NO];
            [self updateButtonsAlpha];
        }
    }

}

-(void)featureButtonClicked:(id)sender
{
    //subclasses override this method
}

- (void)forwardButtonClicked:(id)sender {
    [self scrollToPage:++prefferedNextPageIndex animated:YES];
}

- (void)backwardButtonClicked:(id)sender {
    [self scrollToPage:--prefferedNextPageIndex animated:YES];
}


-(void)scrollToPage:(int)page animated:(bool)animate{
    if (page < 0 || page >= self.featureButtons.count) {
        return;
    }
    if (animate) {
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [self.scrollView setContentOffset:CGPointMake(page * self.scrollView.frame.size.width, 0)];
            [self.scrollView layoutIfNeeded];
        } completion:^(BOOL finished) {
            if (finished) {
                prefferedNextPageIndex = currentPageIndex;
            }
        }];
    }else{
        [self.scrollView setContentOffset:CGPointMake(page * self.scrollView.frame.size.width, 0)];
        prefferedNextPageIndex = currentPageIndex;
    }
}


#pragma mark ScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int pageIndex = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;
    if (pageIndex != currentPageIndex)
    {
        currentPageIndex = pageIndex;
    }
    [self updateButtonsAlpha];
}

-(void)updateButtonsAlpha
{
    if (self.scrollView.contentOffset.x < 200) {
        [self.backwardButton setAlpha:self.scrollView.contentOffset.x / 200];
    } else{
        [self.backwardButton setAlpha:1];
    }
    
    if (self.scrollView.contentOffset.x > (self.scrollView.contentSize.width - self.scrollView.frame.size.width)-200) {
        [self.forwardButton setAlpha:(self.scrollView.contentSize.width - self.scrollView.frame.size.width - self.scrollView.contentOffset.x) / 200];
    } else{
        [self.forwardButton setAlpha:1];
    }

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    prefferedNextPageIndex = currentPageIndex;
}


@end
